<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小蚕活动平台</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- Vue.js -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios for HTTP requests -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    <!-- 引入自定义样式 -->
    <link rel="stylesheet" href="css/index.css">
</head>
<body>
    <div id="app">
        <div class="container">
            <!-- 导航栏 -->
            <nav class="navbar">
                <a href="#" class="navbar-brand">
                    🐛 小蚕活动平台
                </a>
                <div class="navbar-nav">
                    <a href="#" class="nav-link active">
                        🏠 首页
                    </a>
                    <a href="/location.html" class="nav-link">
                        📍 地址管理
                    </a>
                    <a href="/notify.html" class="nav-link">
                        🔔 通知管理
                    </a>
                </div>
            </nav>
            
            <!-- 头部搜索区域 -->
            <div class="header fade-in">
                <h1 class="header-title">🐛 门店查询</h1>
                <div class="search-section">
                    <!-- 地址选择器 -->
                    <div class="address-selector">
                        <el-select
                            v-model="selectedAddressId"
                            :placeholder="addressOptions.length === 0 ? '请输入关键词搜索地址' : '选择已保存的地址'"
                            filterable
                            remote
                            reserve-keyword
                            :remote-method="searchAddresses"
                            :loading="addressLoading"
                            clearable
                            @change="handleAddressChange"
                            @focus="loadLocalAddresses"
                            style="width: 100%"
                        >
                            <el-option
                                v-for="address in addressOptions"
                                :key="address.id"
                                :label="getAddressDisplayName(address)"
                                :value="address.id"
                            >
                                <div class="address-item">
                                    <div class="address-title">{{ getAddressDisplayName(address) }}</div>
                                    <div class="address-detail">{{ address.address }}</div>
                                </div>
                            </el-option>
                        </el-select>
                    </div>
                    
                    <div style="display: flex; gap: 10px; align-items: center;" class="search-input">
                        <el-input
                            v-model="searchForm.name"
                            placeholder="请输入门店名称"
                            clearable
                            @keyup.enter.native="handleSearch"
                            style="flex: 1;"
                        ></el-input>
                        <el-button 
                            type="primary" 
                            icon="el-icon-search"
                            @click="handleSearch"
                            :loading="loading"
                        >
                            搜索
                        </el-button>
                    </div>
                    
                    <div class="sort-buttons">
                        <el-button-group>
                            <el-button
                                :type="searchForm.orderType === 1 ? 'primary' : 'default'"
                                @click="handleSort(1)"
                            >
                                默认排序
                            </el-button>
                            <el-button
                                :type="searchForm.orderType === 2 ? 'primary' : 'default'"
                                @click="handleSort(2)"
                            >
                                返现金额
                            </el-button>
                            <el-button
                                :type="searchForm.orderType === 3 ? 'primary' : 'default'"
                                @click="handleSort(3)"
                            >
                                返现比例
                            </el-button>
                        </el-button-group>
                        
                        <el-switch
                            v-model="searchForm.onlyAvailable"
                            active-text="只看可抢"
                            inactive-text="显示全部"
                            @change="handleSearch"
                            style="margin-left: 15px;"
                        ></el-switch>
                    </div>
                </div>
            </div>
            
            <!-- 内容区域 -->
            <div class="content">
                <!-- 加载状态 -->
                <div v-if="loading" class="loading-container">
                    <div class="loading-content">
                        <i class="el-icon-loading"></i>
                        <span>正在加载门店信息...</span>
                    </div>
                </div>
                
                <!-- 空状态 -->
                <div v-else-if="storeList.length === 0" class="empty-state">
                    <div class="empty-icon">🏪</div>
                    <h3>暂无门店信息</h3>
                    <p>请尝试调整搜索条件或稍后再试</p>
                </div>
                
                <!-- 门店列表 -->
                <div v-else>
                    <div 
                        v-for="(store, index) in storeList" 
                        :key="store.promotionId"
                        class="store-card bounce-in"
                        :class="{ 'sold-out': store.leftNumber <= 0 }"
                        :style="{ animationDelay: (index * 0.1) + 's' }"
                    >
                        <div class="store-item">
                            <!-- 门店图片 -->
                            <div class="store-image">
                                <img v-if="store.icon" :src="store.icon" :alt="store.name" />
                                <span v-else>{{ store.name.charAt(0) }}</span>
                            </div>
                            
                            <!-- 门店信息 -->
                            <div class="store-info">
                                <div class="store-name">
                                    {{ store.name }}
                                    <span v-if="store.ifNew" class="new-badge">新店</span>
                                    <span :class="getPlatformClass(store.type)">{{ getPlatformName(store.type) }}</span>
                                </div>
                                
                                <div class="store-details">
                                    <div class="detail-item">
                                        <i class="detail-icon el-icon-time"></i>
                                        <span>营业时间：{{ store.openHours }}</span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="detail-icon el-icon-money"></i>
                                        <span>满{{ store.price }}返<span class="highlight">{{ store.rebatePrice }}</span></span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="detail-icon el-icon-clock"></i>
                                        <span>活动时间：{{ store.startTime }} - {{ store.endTime }}</span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="detail-icon el-icon-goods"></i>
                                        <span>剩余数量：<span :class="store.leftNumber > 0 ? 'success' : 'zero-stock'">
                                            {{ store.leftNumber > 0 ? store.leftNumber : '已售罄' }}
                                        </span></span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="detail-icon el-icon-star-on"></i>
                                        <span>好评条件：{{ getRebateConditionText(store.rebateCondition) }}</span>
                                    </div>
                                    <div class="detail-item">
                                        <i class="detail-icon el-icon-location-outline"></i>
                                        <span>距离：{{ formatDistance(store.distance) }}</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 操作按钮 -->
                            <div class="store-actions">

                                <el-button
                                    v-if="store.leftNumber <= 0"
                                    type="success"
                                    size="small"
                                    class="action-button"
                                    @click="handleBook(store)"
                                    :loading="actionLoading[store.promotionId + '_book']"
                                >
                                   可抢通知
                                </el-button>

                            </div>
                        </div>
                    </div>
                    
                    <!-- 通知配置对话框 -->
                    <el-dialog
                        title="🔔 可抢通知配置"
                        :visible.sync="notifyConfigVisible"
                        width="420px"
                        :close-on-click-modal="false"
                        :modal-append-to-body="true"
                        :append-to-body="true"
                        custom-class="notify-config-dialog"
                        :before-close="handleDialogClose"
                    >
                        <div class="dialog-content">
                            <!-- 门店信息展示 -->
                            <div v-if="currentNotifyStore" class="store-preview">
                                <div class="store-preview-icon">
                                    <img v-if="currentNotifyStore.icon" :src="currentNotifyStore.icon" :alt="currentNotifyStore.name" />
                                    <span v-else>{{ currentNotifyStore.name.charAt(0) }}</span>
                                </div>
                                <div class="store-preview-info">
                                    <div class="store-preview-name">{{ currentNotifyStore.name }}</div>
                                    <div class="store-preview-detail">满{{ currentNotifyStore.price }}返{{ currentNotifyStore.rebatePrice }}元</div>
                                </div>
                            </div>
                            
                            <el-form :model="notifyConfigForm" :rules="notifyConfigRules" ref="notifyConfigForm" label-width="100px" class="config-form">
                                <el-form-item label="通知方式" prop="onlyOne">
                                    <el-radio-group v-model="notifyConfigForm.onlyOne" @change="handleRadioChange">
                                        <el-radio :label="true" class="radio-option" :class="{ 'selected': notifyConfigForm.onlyOne === true }">
                                            <div class="radio-content">
                                                <div class="radio-title">🎯 只通知一次</div>
                                                <div class="radio-desc">有库存时立即通知，通知后自动取消</div>
                                            </div>
                                        </el-radio>
                                        <el-radio :label="false" class="radio-option" :class="{ 'selected': notifyConfigForm.onlyOne === false }">
                                            <div class="radio-content">
                                                <div class="radio-title">🔄 持续通知</div>
                                                <div class="radio-desc">每次有库存时都会通知，直到手动取消</div>
                                            </div>
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                
                                <el-form-item label="有效期" prop="expireDay">
                                    <div class="expire-setting">
                                        <el-input-number
                                            v-model="notifyConfigForm.expireDay"
                                            :min="1"
                                            :max="365"
                                            controls-position="right"
                                            placeholder="永久有效"
                                            style="width: 140px"
                                        ></el-input-number>
                                        <span class="expire-unit">天</span>
                                        <el-button 
                                            v-if="notifyConfigForm.expireDay" 
                                            size="mini" 
                                            type="text" 
                                            @click="notifyConfigForm.expireDay = null"
                                            class="clear-expire"
                                        >
                                            清除
                                        </el-button>
                                    </div>
                                    <div class="expire-tip">
                                        💡 不设置有效期则永久有效，建议设置7-30天
                                    </div>
                                </el-form-item>
                            </el-form>
                        </div>
                        
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="handleDialogClose" class="cancel-btn">
                                <i class="el-icon-close"></i>
                                取消
                            </el-button>
                            <el-button type="primary" @click="handleNotifyConfigSave" :loading="notifyConfigSaving" class="confirm-btn">
                                <i class="el-icon-check"></i>
                                {{ notifyConfigSaving ? '保存中...' : '确定配置' }}
                            </el-button>
                        </div>
                    </el-dialog>
                    
                    <!-- 滚动加载更多指示器 -->
                    <div class="scroll-loading-container" v-if="storeList.length > 0">
                        <div 
                            v-if="pagination.isLoadingMore" 
                            class="loading-more"
                        >
                            <i class="el-icon-loading"></i>
                            <span>正在加载更多...</span>
                        </div>
                        
                        <div 
                            v-else-if="!pagination.hasNextPage" 
                            class="no-more-data"
                        >
                            <i class="el-icon-circle-check"></i>
                            <span>已加载全部数据</span>
                        </div>
                        
                        <div 
                            v-else 
                            class="load-more-trigger"
                            ref="loadMoreTrigger"
                        >
                            <span>向下滚动加载更多</span>
                        </div>
                        
                        <div class="pagination-info">
                            已加载 {{ storeList.length }} 条记录
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    loading: false,
                    actionLoading: {},
                    searchForm: {
                        name: '',
                        orderType: 1,
                        cityCode: null,
                        latitude: '',
                        longitude: '',
                        onlyAvailable: false,
                        pageNum: 1,
                        pageSize: 30
                    },
                    pagination: {
                        currentPage: 1,
                        hasNextPage: true,
                        isLoadingMore: false
                    },
                    // 滚动监听相关
                    scrollObserver: null,
                    storeList: [],
                    // 地址选择相关
                    selectedAddress: null,
                    selectedAddressId: null,
                    addressOptions: [],
                    addressLoading: false,
                    // 通知配置相关
                    notifyConfigVisible: false,
                    notifyConfigSaving: false,
                    notifyConfigForm: {
                        onlyOne: false,
                        expireDay: null
                    },
                    notifyConfigRules: {
                        onlyOne: [
                            { required: true, message: '请选择是否只通知一次', trigger: 'change' }
                        ]
                    },
                    currentNotifyStore: null, // 当前配置通知的门店
                    defaultCityCode: 110100 // 默认北京市城市编码
                }
            },
            mounted() {
                // 添加全局错误处理来忽略浏览器扩展相关错误
                window.addEventListener('error', function(e) {
                    if (e.message && e.message.includes('message port closed')) {
                        // 静默忽略浏览器扩展相关错误
                        e.preventDefault();
                        return false;
                    }
                });
                
                this.getCurrentLocation();
                this.loadSavedAddress();
                this.loadDefaultAddress();
                
                // 初始化滚动监听
                this.initScrollObserver();
                
                // 监听页面可见性变化，当从其他页面返回时刷新地址列表
          /*      document.addEventListener('visibilitychange', () => {
                    if (!document.hidden) {
                        // 页面变为可见时，刷新地址列表
                        this.refreshAddresses();
                    }
                });*/
            },
            beforeDestroy() {
                // 清理滚动监听器
                if (this.scrollObserver) {
                    this.scrollObserver.disconnect();
                }
            },
            computed: {
                // 计算当前已加载的页数
                loadedPages() {
                    return Math.ceil(this.storeList.length / this.searchForm.pageSize);
                }
            },
            methods: {
                // 搜索门店
                async handleSearch(resetPage = true) {
                    if (resetPage) {
                        // 重新搜索时重置分页（按规范pageNum从1开始）
                        this.searchForm.pageNum = 1;
                        this.pagination.currentPage = 1;
                        this.pagination.hasNextPage = true;
                    }
                    
                    this.loading = resetPage; // 只有重新搜索时才显示主加载状态
                    
                    try {
                        const response = await axios.post('/api/xiaochan/query', this.searchForm);
                        if (response.data.success) {
                            const newData = response.data.data || [];
                            
                            if (resetPage) {
                                // 新搜索，替换数据
                                this.storeList = newData;
                                console.log(`新搜索完成，获取到 ${newData.length} 条数据`);
                            } else {
                                // 加载更多，将数据追加到现有列表末尾（无限滚动核心逻辑）
                                this.storeList = [...this.storeList, ...newData];
                                console.log(`加载第 ${this.pagination.currentPage} 页，新增 ${newData.length} 条数据，总计 ${this.storeList.length} 条`);
                            }
                            
                            // 严格按照项目规范：返回数据量小于pageSize时判定无下一页
                            this.pagination.hasNextPage = newData.length >= this.searchForm.pageSize;
                            
                            if (!this.pagination.hasNextPage && !resetPage) {
                                console.log('已加载全部数据，无更多数据');
                            }
                            
                        } else {
                            this.$message.error(response.data.msg || '查询失败');
                            if (!resetPage) {
                                // 加载失败时回退页码
                                this.pagination.currentPage--;
                                this.searchForm.pageNum = this.pagination.currentPage;
                            }
                        }
                    } catch (error) {
                        console.error('查询失败:', error);
                        this.$message.error('网络错误，请稍后重试');
                        if (!resetPage) {
                            // 加载失败时回退页码
                            this.pagination.currentPage--;
                            this.searchForm.pageNum = this.pagination.currentPage;
                        }
                    } finally {
                        this.loading = false;
                        this.pagination.isLoadingMore = false;
                        
                        // DOM更新后重新初始化滚动监听器
                        this.$nextTick(() => {
                            this.reinitScrollObserver();
                        });
                    }
                },
                
                // 排序处理
                handleSort(orderType) {
                    this.searchForm.orderType = orderType;
                    this.handleSearch();
                },
                
                // 初始化滚动监听器（无限滚动的核心实现）
                initScrollObserver() {
                    this.$nextTick(() => {
                        // 使用 Intersection Observer API 实现高性能滚动监听
                        if (this.$refs.loadMoreTrigger) {
                            this.scrollObserver = new IntersectionObserver(
                                (entries) => {
                                    entries.forEach(entry => {
                                        if (entry.isIntersecting && 
                                            this.pagination.hasNextPage && 
                                            !this.pagination.isLoadingMore && 
                                            !this.loading) {
                                            
                                            console.log('触发无限滚动加载');
                                            // 触发元素进入可视区域，自动加载下一页
                                            this.loadNextPage();
                                        }
                                    });
                                },
                                {
                                    // 提前300px触发加载，提升用户体验
                                    rootMargin: '300px',
                                    // 设置阈值，确保触发的准确性
                                    threshold: 0.1
                                }
                            );
                            
                            this.scrollObserver.observe(this.$refs.loadMoreTrigger);
                            console.log('无限滚动监听器已初始化');
                        }
                    });
                },
                
                // 重新初始化滚动监听器（在数据更新后调用）
                reinitScrollObserver() {
                    if (this.scrollObserver) {
                        this.scrollObserver.disconnect();
                    }
                    this.initScrollObserver();
                },
                
                // 加载下一页（无限滚动核心方法）
                async loadNextPage() {
                    if (!this.pagination.hasNextPage || this.pagination.isLoadingMore || this.loading) {
                        console.log('跳过加载：', {
                            hasNextPage: this.pagination.hasNextPage,
                            isLoadingMore: this.pagination.isLoadingMore,
                            loading: this.loading
                        });
                        return;
                    }
                    
                    console.log(`开始加载第 ${this.pagination.currentPage + 1} 页`);
                    this.pagination.isLoadingMore = true;
                    
                    // 按照项目规范更新页码（从1开始）
                    this.pagination.currentPage++;
                    this.searchForm.pageNum = this.pagination.currentPage;
                    
                    // 关键：传入false确保数据追加而不是替换
                    await this.handleSearch(false);
                },
                
                // 刷新已加载数据（保持无限滚动状态）
                async refreshCurrentPageData() {
                    // 保存当前的分页状态和列表长度
                    const originalPageNum = this.searchForm.pageNum;
                    const originalCurrentPage = this.pagination.currentPage;
                    const currentDataLength = this.storeList.length;
                    
                    console.log(`开始刷新数据，当前已加载 ${originalCurrentPage} 页，共 ${currentDataLength} 条数据`);
                    
                    try {
                        let allData = [];
                        
                        // 重新加载所有已加载页面的数据，保持无限滚动的连续性
                        for (let page = 1; page <= originalCurrentPage; page++) {
                            this.searchForm.pageNum = page;
                            const pageResponse = await axios.post('/api/xiaochan/query', this.searchForm);
                            
                            if (pageResponse.data.success && pageResponse.data.data) {
                                const pageData = pageResponse.data.data;
                                // 将每页数据追加到总数据中
                                allData = [...allData, ...pageData];
                                
                                console.log(`刷新第 ${page} 页完成，获取 ${pageData.length} 条数据`);
                                
                                // 按照项目规范判断是否还有下一页
                                if (page === originalCurrentPage) {
                                    this.pagination.hasNextPage = pageData.length >= this.searchForm.pageSize;
                                }
                                
                                if (pageData.length < this.searchForm.pageSize) {
                                    this.pagination.hasNextPage = false;
                                    break;
                                }
                            } else {
                                console.error(`刷新第 ${page} 页失败`);
                                break;
                            }
                        }
                        
                        // 更新列表数据，保持原有的滚动状态
                        this.storeList = allData;
                        console.log(`数据刷新完成，总计 ${allData.length} 条数据`);
                        
                        // 重新初始化滚动监听器
                        this.$nextTick(() => {
                            this.reinitScrollObserver();
                        });
                        
                    } catch (error) {
                        console.error('刷新数据失败:', error);
                        this.$message.error('刷新数据失败，请稍后重试');
                    } finally {
                        // 恢复原有的分页状态
                        this.searchForm.pageNum = originalPageNum;
                        this.pagination.currentPage = originalCurrentPage;
                    }
                },
                
                // 报名
                async handleApply(store) {
                    const loadingKey = store.promotionId + '_apply';
                    this.$set(this.actionLoading, loadingKey, true);
                    
                    try {
                        const response = await axios.post(`/api/xiaochan/apply/${store.promotionId}`);
                        if (response.data.success) {
                            this.$message.success('报名成功！');
                            // 只更新当前页数据，不重置整个列表
                            this.refreshCurrentPageData();
                        } else {
                            this.$message.error(response.data.msg || '报名失败');
                        }
                    } catch (error) {
                        console.error('报名失败:', error);
                        this.$message.error('网络错误，请稍后重试');
                    } finally {
                        this.$set(this.actionLoading, loadingKey, false);
                    }
                },
                
                // 预约
                async handleBook(store) {
                    // 设置当前配置的门店信息
                    this.currentNotifyStore = store;
                    
                    // 重置表单
                    this.notifyConfigForm = {
                        onlyOne: false,
                        expireDay: null
                    };
                    
                    // 显示配置对话框
                    this.notifyConfigVisible = true;
                },
                
                // 忽略
                async handleIgnore(store) {
                    const loadingKey = store.storeId + '_ignore';
                    this.$set(this.actionLoading, loadingKey, true);
                    
                    try {
                        const ignoreData = {
                            storeId: store.storeId.toString(),
                            storeName: store.name,
                            type: store.type,
                            price: store.price,
                            rebatePrice: store.rebatePrice,
                            rebateCondition: store.rebateCondition,
                            icon: store.icon
                        };
                        const response = await axios.post('/api/xiaochan/ignore', ignoreData);
                        if (response.data.success) {
                            this.$message.success('已忽略该门店');
                            // 只更新当前页数据，不重置整个列表
                            this.refreshCurrentPageData();
                        } else {
                            this.$message.error(response.data.msg || '操作失败');
                        }
                    } catch (error) {
                        console.error('忽略失败:', error);
                        this.$message.error('网络错误，请稍后重试');
                    } finally {
                        this.$set(this.actionLoading, loadingKey, false);
                    }
                },
                
                // 获取平台名称
                getPlatformName(type) {
                    const platforms = {
                        1: '美团',
                        2: '饿了么',
                        3: '京东'
                    };
                    return platforms[type] || '未知';
                },
                
                // 获取平台样式类
                getPlatformClass(type) {
                    const classes = {
                        1: 'platform-tag platform-meituan',
                        2: 'platform-tag platform-eleme',
                        3: 'platform-tag platform-jd'
                    };
                    return classes[type] || 'platform-tag';
                },
                
                // 获取好评条件文本
                getRebateConditionText(condition) {
                    const conditions = {
                        99: '无需评价',
                        2: '图文评价'
                    };
                    return conditions[condition] || '其他';
                },
                
                // 格式化距离
                formatDistance(distance) {
                    if (distance < 1000) {
                        return distance + 'm';
                    } else {
                        return (distance / 1000).toFixed(1) + 'km';
                    }
                },
                
                // 判断是否可以报名
                canApply(store) {
                    if (store.leftNumber <= 0) return false;
                    
                    // 检查当前时间是否在活动时间内
                    const now = new Date();
                    const currentTime = now.getHours().toString().padStart(2, '0') + ':' + 
                                      now.getMinutes().toString().padStart(2, '0');
                    
                    return currentTime >= store.startTime && currentTime <= store.endTime;
                },
                
                // 获取当前位置
                getCurrentLocation() {
                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(
                            (position) => {
                                this.searchForm.latitude = position.coords.latitude.toString();
                                this.searchForm.longitude = position.coords.longitude.toString();
                            },
                            (error) => {
                                console.log('获取位置失败:', error);
                            }
                        );
                    }
                },
                
            
                // 跳转到地址选择页面
                goToAddressPage() {
                    window.open('/location.html', '_blank');
                },
                
                // 搜索地址 - 如果有关键字则搜索远程地址，否则加载本地保存的地址
                async searchAddresses(keyword) {
                    if (!keyword || keyword.trim().length < 2) {
                        // 没有关键字时，重新加载本地保存的地址列表
                        await this.loadLocalAddresses();
                        return;
                    }
                    
                    this.addressLoading = true;
                    this.addressSearchKeyword = keyword;
                    
                    try {
                        // 使用当前选中地址的cityCode，如果没有则使用默认城市编码
                        const cityCode = this.selectedAddress?.cityCode || this.defaultCityCode;
                        const response = await axios.get('/api/location/searchAddress', {
                            params: {
                                keyword: keyword.trim(),
                                cityCode: cityCode
                            }
                        });
                        
                        if (response.data.success) {
                            const searchResults = response.data.data || [];
                            // 为搜索结果添加标记，便于区分本地地址和搜索结果
                            searchResults.forEach(addr => {
                                addr._isSearchResult = true;
                                // 为AddressVO结构添加name字段，保证与本地地址的一致性
                                if (!addr.name && addr.title) {
                                    addr.name = addr.title;
                                }
                            });
                            this.addressOptions = searchResults;
                        } else {
                            this.$message.error(response.data.msg || '地址搜索失败');
                            this.addressOptions = [];
                        }
                    } catch (error) {
                        console.error('地址搜索失败:', error);
                        this.$message.error('网络错误，请稍后重试');
                        this.addressOptions = [];
                    } finally {
                        this.addressLoading = false;
                    }
                },
                
                // 加载本地保存的地址列表
                async loadLocalAddresses() {
                    try {
                        const response = await axios.get('/api/location');
                        if (response.data.success && response.data.data) {
                            // 为本地地址添加标记
                            const localAddresses = response.data.data;
                            localAddresses.forEach(addr => {
                                addr._isLocalAddress = true;
                            });
                            this.addressOptions = localAddresses;
                        }
                    } catch (error) {
                        console.error('加载本地地址失败:', error);
                    }
                },
                
                // 处理地址选择变化
                handleAddressChange(selectedAddressId) {
                    if (selectedAddressId) {
                        // 根据ID找到对应的地址对象
                        const selectedAddress = this.findAddressById(selectedAddressId);
                        if (selectedAddress) {
                            this.selectedAddress = selectedAddress;
                            
                            // 更新搜索表单中的地址相关参数
                            this.searchForm.cityCode = parseInt(selectedAddress.cityCode);
                            this.searchForm.latitude = selectedAddress.latitude;
                            this.searchForm.longitude = selectedAddress.longitude;
                            
                            // 保存用户选择的地址ID到localStorage
                            this.saveSelectedAddressId(selectedAddressId);
                            
                            const displayName = this.getAddressDisplayName(selectedAddress);
                            this.$message.success(`已选择地址: ${displayName}`);
                            
                            // 自动触发搜索
                            this.handleSearch();
                        }
                    } else {
                        // 清空地址选择时，恢复默认值
                        this.selectedAddress = null;
                        this.searchForm.cityCode = null;
                        this.searchForm.latitude = '';
                        this.searchForm.longitude = '';
                        
                        // 清除保存的地址ID
                        localStorage.removeItem('selectedAddressId');
                    }
                },
                
                // 加载默认地址（获取地址列表并选中第一个或上次选择的地址）
                async loadDefaultAddress() {
                    try {
                        // 调用LocationController的getAll方法获取地址列表
                        const response = await axios.get('/api/location');
                        
                        if (response.data.success && response.data.data && response.data.data.length > 0) {
                            this.addressOptions = response.data.data;
                            console.log('成功获取地址列表:', this.addressOptions.length, '个地址');
                            
                            // 输出地址列表的详细信息，便于调试
                            this.addressOptions.forEach((addr, index) => {
                                console.log(`地址 ${index + 1}: ID=${addr.id}, 名称=${addr.name}`);
                            });
                            
                            // 检查是否有保存的地址ID
                            const savedAddressId = this.getSavedAddressId();
                            console.log('保存的地址ID:', savedAddressId);
                            
                            if (savedAddressId) {
                                // 根据保存的ID在地址列表中查找对应的地址
                                const foundAddress = this.findAddressById(savedAddressId);
                                if (foundAddress) {
                                    this.selectedAddressId = savedAddressId;
                                    this.selectedAddress = foundAddress;
                                    // 直接设置搜索表单参数，不触发change事件避免循环
                                    this.searchForm.cityCode = parseInt(foundAddress.cityCode);
                                    this.searchForm.latitude = foundAddress.latitude;
                                    this.searchForm.longitude = foundAddress.longitude;
                                    
                                    const displayName = this.getAddressDisplayName(foundAddress);
                                    console.log('成功恢复保存的地址:', displayName, ', ID:', foundAddress.id);
                                    
                                    // 重要：恢复地址后自动触发搜索，获取门店数据
                                    this.handleSearch();
                                    return;
                                } else {
                                    // 如果根据ID找不到地址，清除无效的保存数据
                                    localStorage.removeItem('selectedAddressId');
                                    console.log('保存的地址ID无效，已清除。保存的ID:', savedAddressId);
                                }
                            }
                            
                            // 如果没有保存的地址或找不到保存的地址，选择第一个地址
                            const firstAddress = this.addressOptions[0];
                            this.selectedAddressId = firstAddress.id;
                            this.selectedAddress = firstAddress;
                            // 直接设置搜索表单参数
                            this.searchForm.cityCode = parseInt(firstAddress.cityCode);
                            this.searchForm.latitude = firstAddress.latitude;
                            this.searchForm.longitude = firstAddress.longitude;
                            
                            // 保存默认选择
                            this.saveSelectedAddressId(firstAddress.id);
                            
                            const displayName = this.getAddressDisplayName(firstAddress);
                            console.log('使用默认地址(第一个):', displayName, ', ID:', firstAddress.id);
                            
                            // 重要：使用默认地址后也要自动触发搜索，获取门店数据
                            this.handleSearch();
                        } else {
                            console.log('地址列表为空，提示用户创建地址');
                            // 地址列表为空，提示用户创建地址
                            this.showCreateAddressPrompt();
                        }
                    } catch (error) {
                        console.error('获取地址列表失败:', error);
                        this.$message.error('获取地址列表失败: ' + (error.response?.data?.msg || error.message));
                        // 网络错误时也提示用户创建地址
                        this.showCreateAddressPrompt();
                    }
                },
                
                // 显示创建地址提示
                showCreateAddressPrompt() {
                    this.$confirm('暂无地址信息，是否前往创建地址？', '提示', {
                        confirmButtonText: '创建地址',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        this.goToAddressPage();
                    }).catch(() => {
                        // 用户取消，使用默认搜索参数
                        this.searchForm.cityCode = this.defaultCityCode;
                        // 用户取消创建地址后，也要触发搜索获取门店数据
                        this.handleSearch();
                    });
                },
                
                // 刷新地址列表（在从地址管理页面返回时可以调用）
                async refreshAddresses() {
                    await this.loadDefaultAddress();
                },
                
                // 保存用户选择的地址ID到localStorage
                saveSelectedAddressId(addressId) {
                    try {
                        console.log('保存地址选择，ID:', addressId);
                        localStorage.setItem('selectedAddressId', addressId);
                        console.log('已保存地址ID到localStorage:', addressId);
                    } catch (error) {
                        console.error('保存地址ID失败:', error);
                    }
                },
                
                // 获取地址显示名称（兼容Location和AddressVO两种数据结构）
                getAddressDisplayName(address) {
                    // Location模型使用name字段，AddressVO模型使用title字段
                    return address.name || address.title || '未知地址';
                },
                
                // 从localStorage获取保存的地址ID
                getSavedAddressId() {
                    try {
                        return localStorage.getItem('selectedAddressId');
                    } catch (error) {
                        console.error('获取保存的地址ID失败:', error);
                        return null;
                    }
                },
                
                // 根据保存的地址ID从地址列表中找到对应的地址对象
                findAddressById(addressId) {
                    if (!addressId || !this.addressOptions.length) {
                        return null;
                    }
                    return this.addressOptions.find(addr => addr.id === addressId);
                },
                
                // 处理对话框关闭
                handleDialogClose() {
                    this.notifyConfigVisible = false;
                    // 重置表单和当前门店信息
                    this.currentNotifyStore = null;
                    if (this.$refs.notifyConfigForm) {
                        this.$refs.notifyConfigForm.resetFields();
                    }
                },
                
                // 保存通知配置
                async handleNotifyConfigSave() {
                    // 表单校验
                    try {
                        await this.$refs.notifyConfigForm.validate();
                    } catch (error) {
                        return;
                    }
                    
                    if (!this.currentNotifyStore) {
                        this.$message.error('门店信息丢失，请重新操作');
                        return;
                    }
                    
                    this.notifyConfigSaving = true;
                    
                    try {
                        const configData = {
                            type: 1, // 1：指定门店活动提醒
                            location: this.selectedAddress, // 当前选中的地址
                            storeExtNotifyConfig: {
                                storeInfo: this.currentNotifyStore,
                                onlyOne:this.notifyConfigForm.onlyOne,
                                expireDay: this.notifyConfigForm.expireDay,
                            },
                        };
                        
                        const response = await axios.post('/api/notify/config', configData);
                        if (response.data.success) {
                            this.$message({
                                message: '🎉 通知配置保存成功！',
                                type: 'success',
                                duration: 3000,
                                showClose: true
                            });
                            this.handleDialogClose();
                        } else {
                            this.$message.error(response.data.msg || '保存失败');
                        }
                    } catch (error) {
                        console.error('保存通知配置失败:', error);
                        this.$message.error('网络错误，请稍后重试');
                    } finally {
                        this.notifyConfigSaving = false;
                    }
                },
                
                // 加载保存的地址（在页面初始化时调用）
                loadSavedAddress() {
                    // 注意：此方法在页面初始化时调用，此时地址列表可能还未加载
                    // 实际的地址恢复逻辑在loadDefaultAddress方法中处理
                    const savedAddressId = this.getSavedAddressId();
                    if (savedAddressId) {
                        console.log('发现保存的地址ID:', savedAddressId);
                    }
                },
                
                // 处理radio按钮改变事件
                handleRadioChange(value) {
                    // 确保界面更新
                    this.$nextTick(() => {
                        console.log('Radio选择变更为:', value);
                    });
                }
            }
        });
    </script>
</body>
</html>